import {
  indexApi
} from '../../../api/index';
import {
  request
} from '../../../utils/request';

import Toast from '@vant/weapp/toast/toast';
Page({
  data: {
    defaultData: {
      title: "添加私有商品", // 导航栏标题
      imageSrc: "/images/back.png",
      isBackToPreviousPage: true
    },
    productId: null,
    productName: "", //商品名称
    productCode: "", //产品编号
    pdtModel: "", //产品型号
    productPrice: "", //产品价格
    serviceFee: "", //服务价格
    installationPrice: "", //安装价格
    debuggingPrice: "", //调试价格
    productColor: "", //产品颜色
    serviceDuration: "", //服务时长
    funInfo: "", //功能简介
    productContent: "", //产品详情
    fileListHome: [], //首页图片的列表
    fileListCarousel: [], // 轮播图 
    serviceProList: [], //服务项目范围
    servicePdtList: [], //服务产品范围
    skillsList: [], //技能要求
    serviceTypesList: [], //开放服务
    skills: [],
    serviceProRange: [],
    servicePdtRange: [],
    serviceTypes: [],
    installationPriceError: false,
    productPriceError: false,
    serviceFeeError: false,
    debuggingPriceError: false,
    serviceDurationError: false,
  },

  onLoad(options) {
    Promise.all([this.getDictionary(), this.getServiceTypes()])
      .then(() => {
        if (options.productItem) {
          const productItem = JSON.parse(decodeURIComponent(options.productItem));
          console.log("productItem", productItem);
          const fileListCarousel = productItem.carous ?
            productItem.carous.split(',').map(url => ({
              url
            })) : [];
          const skills = productItem.skills ?
            productItem.skills.split(',') : [];

          const serviceProRange = productItem.serviceProRange ?
            productItem.serviceProRange.split(',') : [];

          const servicePdtRange = productItem.servicePdtRange ?
            productItem.servicePdtRange.split(',') : [];

          const serviceTypes = productItem.serviceTypes ?
            productItem.serviceTypes.split(',') : [];
          this.setData({
            productId: productItem.productId,
            productName: productItem.productName,
            productCode: productItem.productCode,
            pdtModel: productItem.pdtModel,
            productPrice: productItem.productPrice,
            serviceFee: productItem.serviceFee,
            installationPrice: productItem.installationPrice,
            debuggingPrice: productItem.debuggingPrice,
            productColor: productItem.color,
            serviceDuration: productItem.serviceDuration,
            funInfo: productItem.funInfo,
            productContent: productItem.content,
            fileListHome: productItem.productImage ? [{
              url: productItem.productImage
            }] : [],
            fileListCarousel, // 设置轮播图列表
            skills, // 设置技能要求
            serviceProRange, // 设置服务项目范围
            servicePdtRange, // 设置服务产品范围
            serviceTypes // 设置开放服务类型

          })
        }
      })
      .catch(error => {
        console.error("Error occurred while loading:", error);
      });
  },


  // 获取字典
  async getDictionary() {
    try {
      //项目范围
      const resPdt = await request({
        url: indexApi.getSysDicApi("SERVICE_PDT_RANGE"),
        data: {}
      });
      //产品范围
      const resPro = await request({
        url: indexApi.getSysDicApi("SERVICE_PRO_RANGE"),
        data: {}
      });
      //技能要求
      const resSkills = await request({
        url: indexApi.getSysDicApi("PDT_PTY"),
        data: {}
      });

      this.setData({
        servicePdtList: resPdt.data,
        serviceProList: resPro.data,
        skillsList: resSkills.data,
      });

      console.log("servicePdtList", this.data.servicePdtList);
      console.log("serviceProList", this.data.serviceProList);
      console.log("skillsList", this.data.skillsList);
    } catch (error) {
      console.error("Error:", error);
    }
  },

  // 获取系统服务类型
  async getServiceTypes() {
    try {
      const res = await request({
        url: indexApi.getServiceTypesApi(),
        data: {}
      });
      this.setData({
        serviceTypesList: res.data[2].items
      })
      console.log("getDictionary", res.data);
      console.log("getDictionary", res.data[2].items);
    } catch (error) {
      console.error("Error:", error);
    }
  },



  // 商品名称
  productNameChange(event) {
    this.setData({
      productName: event.detail,
    });
    console.log("tpName", this.data.tpName);
  },

  //产品编号
  productCodeChange(event) {
    this.setData({
      productCode: event.detail,
    });
    console.log("productName", this.data.productName);
  },

  //产品型号
  pdtModelChange(event) {
    this.setData({
      pdtModel: event.detail,
    });
    console.log("pdtModel", this.data.pdtModel);
  },

  //产品价格
  productPriceChange(event) {
    const value = event.detail;
    if (value === '') {
      this.setData({
        productPriceError: false,
      });
    }
    // 检查输入是否为有效数字
    else if (!/^\d*\.?\d+$/.test(value)) {
      this.setData({
        productPriceError: true,
      });
    } else {
      this.setData({
        productPrice: value,
        productPriceError: false,
      });
    }
    console.log("productPrice", this.data.productPrice);
  },

  //服务价格
  serviceFeeChange(event) {
    const value = event.detail;
    if (value === '') {
      this.setData({
        serviceFeeError: false,
      });
    }
    // 检查输入是否为有效数字
    else if (!/^\d*\.?\d+$/.test(value)) {
      this.setData({
        serviceFeeError: true,
      });
    } else {
      this.setData({
        serviceFee: value,
        serviceFeeError: false,
      });
    }
    console.log("serviceFee", this.data.serviceFee);
  },

  //安装价格
  installationPriceChange(event) {
    const value = event.detail;
    if (value === '') {
      this.setData({
        installationPriceError: false,
      });
    }
    // 检查输入是否为有效数字
    else if (!/^\d*\.?\d+$/.test(value)) {
      this.setData({
        installationPriceError: true,
      });
    } else {
      this.setData({
        installationPrice: value,
        installationPriceError: false,
      });
    }
  },

  //调试价格
  debuggingPriceChange(event) {
    const value = event.detail;
    if (value === '') {
      this.setData({
        debuggingPriceError: false,
      });
    }
    // 检查输入是否为有效数字
    else if (!/^\d*\.?\d+$/.test(value)) {
      this.setData({
        debuggingPriceError: true,
      });
    } else {
      this.setData({
        debuggingPrice: value,
        debuggingPriceError: false,
      });
    }
    console.log("debuggingPrice", this.data.debuggingPrice);
  },

  //产品颜色
  productColorChange(event) {
    this.setData({
      productColor: event.detail,
    });
    console.log("productColor", this.data.productColor);
  },

  //服务时长
  serviceDurationChange(event) {
    const value = event.detail;
    if (value === '') {
      this.setData({
        serviceDurationError: false,
      });
    }
    // 检查输入是否为有效数字
    else if (!/^\d*\.?\d+$/.test(value)) {
      this.setData({
        serviceDurationError: true,
      });
    } else {
      this.setData({
        serviceDuration: value,
        serviceDurationError: false,
      });
    }

    console.log("serviceDuration", this.data.serviceDuration);
  },

  //功能简介
  funInfoChange(event) {
    this.setData({
      funInfo: event.detail,
    });
    console.log("funInfo", this.data.funInfo);
  },

  //产品详情
  productContentChange(event) {
    this.setData({
      productContent: event.detail,
    });
    console.log("productContent", this.data.productContent);
  },


  // 上传图片
  afterRead(event) {
    const {
      file
    } = event.detail;
    const type = event.currentTarget.dataset.type;
    this.uploadFile(file, type);
  },

  async uploadFile(file, type) {
    try {
      const uploadTask = wx.uploadFile({
        url: indexApi.upLoadApi(),
        header: {
          "Content-Type": "multipart/form-data"
        },
        filePath: file.url,
        name: 'file',
        formData: {},
        success: (res) => {
          const data = JSON.parse(res.data);
          console.log('Upload success', data);
          file.url = data.data;
          if (type == 'home') {
            this.setData({
              fileListHome: [file]
            });
            console.log("fileListHome", this.data.fileListHome);
          } else if (type == 'carousel') {
            let fileListCarousel = this.data.fileListCarousel || [];
            if (fileListCarousel.length < 3) {
              fileListCarousel.push(file);
              this.setData({
                fileListCarousel: fileListCarousel
              });
            }
            console.log("fileListCarousel", this.data.fileListCarousel);
          }
        },
        fail: (err) => {
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          });
        },
      });
    } catch (error) {
      wx.showToast({
        title: '上传失败,请联系管理员',
        icon: 'none'
      });
    }
  },

  // 删除图片
  onDelete(event) {
    const type = event.target.dataset.type;
    const index = event.detail.index;
    if (type === 'home') {
      this.setData({
        fileListHome: []
      });
    } else if (type === 'carousel') {
      let fileListCarousel = this.data.fileListCarousel;
      fileListCarousel.splice(index, 1);
      this.setData({
        fileListCarousel: fileListCarousel
      });
    }
  },

  //技能
  skillsChange(event) {
    console.log("event", event);
    this.setData({
      skills: event.detail
    });
    console.log("skills", this.data.skills);
  },

  // 服务项目范围
  serviceProChange(event) {
    console.log("event", event);
    this.setData({
      serviceProRange: event.detail
    });
    console.log("serviceProRange", this.data.serviceProRange);
  },

  //产品类型
  servicePdtChange(event) {
    console.log("event", event);
    this.setData({
      servicePdtRange: event.detail
    });
    console.log("servicePdtRange", this.data.servicePdtRange);
  },

  // 开放服务
  serviceTypesChange(event) {
    console.log("event", event);
    this.setData({
      serviceTypes: event.detail
    });
    console.log("serviceTypes", this.data.serviceTypes);
  },

  //保存
  async saveTemplate() {
    const {
      productId,
      productName,
      productCode,
      pdtModel,
      productPrice,
      serviceFee,
      installationPrice,
      debuggingPrice,
      productColor, //
      serviceDuration,
      funInfo,
      productContent, //
      fileListHome, //
      fileListCarousel, //
      skills,
      serviceProRange,
      servicePdtRange,
      serviceTypes,
      serviceTypesList,

    } = this.data;

    if (!productName) {
      Toast('请输入商品名称');
      return;
    }
    if (!productPrice) {
      Toast('请输入商品价格');
      return;
    }
    if (!serviceFee) {
      Toast('请输入服务费用');
      return;
    }
    if (!installationPrice) {
      Toast('请输入安装费用');
      return;
    }
    if (!debuggingPrice) {
      Toast('请输入调试费用');
      return;
    }
    if (!serviceDuration) {
      Toast('请输入服务时长');
      return;
    }
    if (fileListHome.length == 0) {
      Toast('请上传产品首图');
      return;
    }
    if (serviceTypes.length == 0) {
      console.log("请选择开放服务");
      Toast('请选择开放服务');
      return;
    }


    let carous = '';
    if (fileListHome.length !== 0) {
      carous = fileListCarousel.map(file => file.url).join(',');
    }
    const newSkills = skills.join(',');
    const newServiceProRange = serviceProRange.join(',');
    const newServicePdtRange = servicePdtRange.join(',');
    let newServiceTypes = ""
    if (serviceTypes.length == 0) {
      newServiceTypes = "1"
    } else {
      newServiceTypes = '1,' + serviceTypes.join(','); // '1,'代表方案报价
    }
    const matchedNames = serviceTypesList
      .filter(item => serviceTypes.includes(String(item.id)))
      .map(item => item.name)
      .join(',');
    const classifyName = "方案报价," + matchedNames;

    console.log(classifyName);
    console.log(carous);
    // 创建请求参数对象
    let requestData = {
      productName,
      productCode,
      pdtModel,
      productPrice,
      serviceFee,
      installationPrice,
      debuggingPrice,
      color: productColor,
      serviceDuration,
      funInfo,
      content: productContent,
      productImage: fileListHome[0].url,
      carous: carous,
      skills: newSkills,
      serviceProRange: newServiceProRange,
      servicePdtRange: newServicePdtRange,
      serviceTypes: newServiceTypes,
      classifyName
    };

    if (productId !== null) {
      requestData.productId = this.data.productId;
    }
    console.log("参数", requestData);

    try {
      const res = await request({
        url: indexApi.addOrUpdateProductForPrivateApi(),
        method: "POST",
        data: requestData, // 动态请求数据
      });
      if (res.code == 200 && productId == null) {
        console.log("productId", productId);
        wx.showToast({
          title: "添加成功",
          icon: "none",
        });
      }
      if (res.code == 200 && productId !== null) {
        console.log("productId", productId);
        wx.showToast({
          title: "修改成功",
          icon: "none",
        });
      }
      console.log("res", res);
      setTimeout(() => {
        wx.navigateBack();
      }, 1000);
    } catch (error) {
      console.error("Error:", error);
    }
  },

  toBack() {
    wx.navigateBack(); 
  }
  

})